<?php

namespace app\admin\controller;

use app\common\model\GiftModel;
use app\common\model\LotteryAwardConfigModel;
use app\common\model\LotteryAwardModel;
use app\common\model\LotteryModel;
use app\common\model\PropsNewModel;
use app\common\model\UserAddressModel;
use app\common\model\UserLotteryHistoryModel;

class RotaryTableController extends BaseController
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $model = LotteryModel::field('*');
            return json([
                'count' => $model->count('id'),
                'list' => $model->order('act_ed_time', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()
                    ->each(function ($query) {
                        $query->status_text = '已失效';
                        if (($act_st_time = strtotime($query->act_st_time)) && ($act_ed_time = strtotime($query->act_ed_time))) {
                            if ($act_st_time < $act_ed_time && $act_st_time < time() && $act_ed_time > time()) {
                                $query->status_text = '生效中';
                            }
                        }

                        if ($query->act_st_time) {
                            $query->act_st_time = str_replace('.000', '', $query->act_st_time);
                        }

                        if ($query->act_ed_time) {
                            $query->act_ed_time = str_replace('.000', '', $query->act_ed_time);
                        }

                        if ($query->diamond_cost) {
                            $query->diamond_cost = bcdiv($query->diamond_cost, '100', 2);
                        }

                        if ($query->gold_cost) {
                            $query->gold_cost = bcdiv($query->gold_cost, '100', 2);
                        }
                    })
                    ->toArray(),
                'msg' => '',
                'code' => 0,
            ]);
        }
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('活动名称不能为空');
            }

            if (!$introduce = trim($this->post('introduce', ''))) {
                return static::bulidFail('活动介绍不能为空');
            }

            if (!$rule_desc = trim($this->post('rule_desc', ''))) {
                return static::bulidFail('活动规则不能为空');
            }

            if (mb_strlen($name) > 20) {
                return static::bulidFail('活动名称长度不能超过20个字符');
            }

            if (mb_strlen($introduce) > 50) {
                return static::bulidFail('活动介绍长度不能超过50个字符');
            }

            if (mb_strlen($rule_desc) > 100) {
                return static::bulidFail('活动规则长度不能超过100个字符');
            }

            if (!$pc_bg_pic = trim($this->post('pc_bg_pic', ''))) {
                return static::bulidFail('PC背景图片不能为空');
            }

            if (!$app_bg_pic = trim($this->post('app_bg_pic', ''))) {
                return static::bulidFail('APP背景图片不能为空');
            }

            if (mb_strpos($pc_bg_pic, 'http://') !== 0 && mb_strpos($pc_bg_pic, 'https://')) {
                return static::bulidFail('PC背景图片地址错误');
            }

            if (mb_strpos($app_bg_pic, 'http://') !== 0 && mb_strpos($app_bg_pic, 'https://')) {
                return static::bulidFail('APP背景图片地址错误');
            }

            if (!in_array($join_user_type = $this->post('join_user_type'), ['0', '1', '2'])) {
                return static::bulidFail('参与用户错误');
            }

            if (!is_numeric($diamond_cost = rtrim(trim($this->post('diamond_cost', '')), '.'))) {
                return static::bulidFail('宝石数量错误');
            }

            if (!is_numeric($gold_cost = rtrim(trim($this->post('gold_cost', '')), '.'))) {
                return static::bulidFail('钻石数量错误');
            }

            if (!$act_st_time_tmp = strtotime($act_st_time = $this->post('act_st_time', ''))) {
                return static::bulidFail('活动开始时间错误');
            }

            if (!$act_ed_time_tmp = strtotime($act_ed_time = $this->post('act_ed_time', ''))) {
                return static::bulidFail('活动结束时间错误');
            }

            if ($act_st_time_tmp >= $act_ed_time_tmp) {
                return static::bulidFail('活动开始时间不能大于等于活动结束时间');
            }

            if ($act_ed_time_tmp <= time()) {
                return static::bulidFail('活动结束时间不能小于当前时间');
            }

            $model = new LotteryModel();
            $model->name = $name;
            $model->introduce = $introduce;
            $model->rule_desc = addslashes($rule_desc); //stripslashes
            $model->pc_bg_pic = $pc_bg_pic;
            $model->app_bg_pic = $app_bg_pic;
            $model->join_user_type = $join_user_type;
            if (bccomp($diamond_cost, '0', 2) === 1) {
                $model->diamond_cost = bcmul($diamond_cost, '100', '0');
            } else {
                $model->diamond_cost = 0;
            }

            if (bccomp($gold_cost, '0', 2) === 1) {
                $model->gold_cost = bcmul($gold_cost, '100', '0');
            } else {
                $model->gold_cost = 0;
            }

            $model->act_st_time = $act_st_time;
            $model->act_ed_time = $act_ed_time;
            $model->operator = $this->admin_name;

            if (!$model->save()) {
                return static::bulidFail('创建活动失败');
            }

            $this->addAdminLog('创建了转盘抽奖活动 活动ID:' . $model->id, 0);

            return static::bulidSuccess([], '创建活动成功');
        }

        return $this->fetch();
    }

    public function edit()
    {
        if (!$id = $this->get('id')) {
            return static::bulidFail('活动ID错误');
        }

        if (!$model = LotteryModel::where('id', $id)->find()) {
            return static::bulidFail('活动不存在');
        }

        if ($this->request->isAjax()) {
            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('活动名称不能为空');
            }

            if (!$introduce = trim($this->post('introduce', ''))) {
                return static::bulidFail('活动介绍不能为空');
            }

            if (!$rule_desc = trim($this->post('rule_desc', ''))) {
                return static::bulidFail('活动规则不能为空');
            }

            if (mb_strlen($name) > 20) {
                return static::bulidFail('活动名称长度不能超过20个字符');
            }

            if (mb_strlen($introduce) > 50) {
                return static::bulidFail('活动介绍长度不能超过50个字符');
            }

            if (mb_strlen($rule_desc) > 100) {
                return static::bulidFail('活动规则长度不能超过100个字符');
            }

            if (!$pc_bg_pic = trim($this->post('pc_bg_pic', ''))) {
                return static::bulidFail('PC背景图片不能为空');
            }

            if (!$app_bg_pic = trim($this->post('app_bg_pic', ''))) {
                return static::bulidFail('APP背景图片不能为空');
            }

            if (mb_strpos($pc_bg_pic, 'http://') !== 0 && mb_strpos($pc_bg_pic, 'https://')) {
                return static::bulidFail('PC背景图片地址错误');
            }

            if (mb_strpos($app_bg_pic, 'http://') !== 0 && mb_strpos($app_bg_pic, 'https://')) {
                return static::bulidFail('APP背景图片地址错误');
            }

            if (!in_array($join_user_type = $this->post('join_user_type'), ['0', '1', '2'])) {
                return static::bulidFail('参与用户错误');
            }

            if (!is_numeric($diamond_cost = rtrim(trim($this->post('diamond_cost', '')), '.'))) {
                return static::bulidFail('宝石数量错误');
            }

            if (!is_numeric($gold_cost = rtrim(trim($this->post('gold_cost', '')), '.'))) {
                return static::bulidFail('钻石数量错误');
            }

            if (!$act_st_time_tmp = strtotime($act_st_time = $this->post('act_st_time', ''))) {
                return static::bulidFail('活动开始时间错误');
            }

            if (!$act_ed_time_tmp = strtotime($act_ed_time = $this->post('act_ed_time', ''))) {
                return static::bulidFail('活动结束时间错误');
            }

            if ($act_st_time_tmp >= $act_ed_time_tmp) {
                return static::bulidFail('活动开始时间不能大于等于活动结束时间');
            }

            if ($act_ed_time_tmp <= time()) {
                return static::bulidFail('活动结束时间不能小于当前时间');
            }

            $model->name = $name;
            $model->introduce = $introduce;
            $model->rule_desc = addslashes($rule_desc); //stripslashes
            $model->pc_bg_pic = $pc_bg_pic;
            $model->app_bg_pic = $app_bg_pic;
            $model->join_user_type = $join_user_type;
            if (bccomp($diamond_cost, '0', 2) === 1) {
                $model->diamond_cost = bcmul($diamond_cost, '100', '0');
            } else {
                $model->diamond_cost = 0;
            }

            if (bccomp($gold_cost, '0', 2) === 1) {
                $model->gold_cost = bcmul($gold_cost, '100', '0');
            } else {
                $model->gold_cost = 0;
            }
            $model->act_st_time = $act_st_time;
            $model->act_ed_time = $act_ed_time;
            $model->operator = $this->admin_name;

            if (!$model->save()) {
                return static::bulidFail('编辑活动失败');
            }

            $this->addAdminLog('编辑了转盘抽奖活动 活动ID:' . $model->id, 0);

            return static::bulidSuccess([], '编辑活动成功');
        }

        $model->rule_desc = stripslashes($model->rule_desc);
        if ($model->diamond_cost != 0) {
            $model->diamond_cost = bcdiv($model->diamond_cost, '100', 2);
        }

        if ($model->gold_cost != 0) {
            $model->gold_cost = bcdiv($model->gold_cost, '100', 2);
        }

        if ($model->act_st_time) {
            $model->act_st_time = str_replace('.000', '', $model->act_st_time);
        }

        if ($model->act_ed_time) {
            $model->act_ed_time = str_replace('.000', '', $model->act_ed_time);
        }

        return $this->assign(['model' => $model])->fetch();
    }

    public function prize()
    {
        if (!$id = $this->get('id', '')) {
            return static::bulidFail('ID非法');
        }

        if (!$model = LotteryModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的活动');
        }

        if ($this->request->isAjax()) {
            if (!($lottery_award_ids = $this->post('lottery_award_id', [])) || !is_array($lottery_award_ids)) {
                return static::bulidFail('编辑的数据错误');
            }

            $lott_num = $this->post('lott_num', []);

            $sort = $this->post('sort', []);

            $data = [];

            foreach ($lottery_award_ids as $key => $value) {
                if (!ctype_digit($value)) {
                    continue;
                }

                $data[] = [
                    'lott_id' => $model->id,
                    'lottery_award_id' => $value,
                    'lott_num' => $lott_num[$key] ?? 1,
                    'sort' => $sort[$key] ?? 0,
                ];
            }

            LotteryAwardConfigModel::destroy(['lott_id' => $model->id]);
            if (!(new LotteryAwardConfigModel())->saveAll($data)) {
                return static::bulidFail('编辑失败');
            }

            $this->addAdminLog('编辑了转盘抽奖配置 活动ID:' . $model->id);

            return static::bulidSuccess([], '编辑成功');
        }

        $conf = LotteryAwardConfigModel::where('lott_id', $model->id)
            ->order('sort', 'desc')
            ->select()
            ->toArray();

        $count = 10 - count($conf);
        for ($i = 0; $i < $count; $i++) {
            $conf[] = [
                'id' => 0,
                'lott_id' => 0,
                'lottery_award_id' => 0,
                'lott_num' => 0,
                'sort' => 0,
            ];
        }

        $list = LotteryAwardModel::where("is_delete", 0)->select()->toArray();
        return $this->assign([
            'list' => $list,
            'stock_nums' => $stock_nums = array_column($list, 'stock_num', 'id'),
            'stock_nums_json' => json_encode($stock_nums, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'model' => $model,
            'conf' => $conf
        ])->fetch();
    }

    public function conf()
    {
        if ($this->request->isAjax()) {
            $model = LotteryAwardModel::field('*');

            if ($name = trim($this->get('name', ''))) {
                $model = $model->whereLike('name', $name . '%');
            }
            $model = $model->where('is_delete', 0);
            return json([
                'count' => $model->count('id'),
                'list' => $model->order('id', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()
                    ->each(function ($query) {
                        $query->remaining = $query->stock_num - $query->used_num;
                    })
                    ->toArray(),
                'msg' => '',
                'code' => 0,
            ]);
        }

        return $this->fetch();
    }

    public function conf_add()
    {
        $props = array_column(PropsNewModel::lists(), 'name', 'id');
        $giftList = [];
        foreach (GiftModel::lists() as $key => $val) {
            if ($val['type'] == 2) {
                $giftList[] = $val;
            }
        }

        $gift = array_column($giftList, 'title', 'id');
        if ($this->request->isAjax()) {
            if (!in_array($award_type = $this->post('award_type'), ['0', '1'])) {
                return static::bulidFail('请选择奖品分类');
            }

            $model = new LotteryAwardModel();
            if ($award_type == 1) {
                if (!$name = trim($this->post('name', ''))) {
                    return static::bulidFail('奖品名称不能为空');
                }
            } else {
                if (!in_array($jp_type = $this->post('jp_type'), ['0', '1', '2', '3', '4', '5', '6'])) {
                    return static::bulidFail('请选择奖品类型');
                }

                if ($jp_type == 3 || $jp_type == 4) {
                    if (!ctype_digit($jp_id = $this->post('jp_id', ''))) {
                        return static::bulidFail('请选择奖品');
                    }
                    if ($jp_type == 4) {
                        $name = $props[$jp_id] ?? '';
                        $model->props_id = $jp_id;
                    } else {
                        $name = $gift[$jp_id] ?? '';
                        $model->gift_id = $jp_id;
                    }
                } else {
                    $name = LotteryAwardModel::AWARD_TYPE[$jp_type];
                }

                $model->virtual_type = $jp_type;
            }

            if (!$desc = trim($this->post('desc', ''))) {
                return static::bulidFail('奖品描述不能为空');
            }

            if (!$award_pic = trim($this->post('award_pic', ''))) {
                return static::bulidFail('请上传奖品图片');
            }

            if (mb_strpos($award_pic, 'http://') !== 0 && mb_strpos($award_pic, 'https://')) {
                return static::bulidFail('奖品图片错误');
            }

            if (!ctype_digit($stock_num = trim($this->post('stock_num', '')))) {
                return static::bulidFail('奖品库存错误 请输入数字');
            }

            if ($stock_num < 0) {
                return static::bulidFail('奖品库存错误 小于0');
            }

            $model->name = $name;
            $model->award_type = $award_type;
            $model->desc = $desc;
            $model->award_pic = $award_pic;
            $model->stock_num = $stock_num;
            $model->created_time = date('Y-m-d H:i:s');
            $model->unit = '';
            $model->operate_admin = $this->admin_name;

            if (!$model->save()) {
                return static::bulidFail('添加奖品失败');
            }

            $this->addAdminLog('添加了奖品:' . $name);

            return static::bulidSuccess([], '添加奖品成功');
        }
        return $this->assign([
            'props' => json_encode($props, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'gift' => json_encode($gift, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
        ])->fetch();
    }

    public function conf_edit()
    {
        if (!$id = $this->get('id', '')) {
            return static::bulidFail('ID非法');
        }

        if (!$model = LotteryAwardModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的奖品');
        }

        if ($this->request->isAjax()) {
            if (!$desc = trim($this->post('desc', ''))) {
                return static::bulidFail('奖品描述不能为空');
            }

            if (!$award_pic = trim($this->post('award_pic', ''))) {
                return static::bulidFail('请上传奖品图片');
            }

            if (mb_strpos($award_pic, 'http://') !== 0 && mb_strpos($award_pic, 'https://')) {
                return static::bulidFail('奖品图片错误');
            }

            if (!ctype_digit($stock_num = trim($this->post('stock_num', '')))) {
                return static::bulidFail('奖品库存错误 请输入数字');
            }

            if ($stock_num < 0) {
                return static::bulidFail('奖品库存错误 小于0');
            }

            $model->desc = $desc;
            $model->award_pic = $award_pic;
            $model->stock_num = $stock_num;
            $model->operate_admin = $this->admin_name;

            if (!$model->save()) {
                return static::bulidFail('编辑奖品失败');
            }

            $this->addAdminLog('编辑了奖品:' . $model->name);

            return static::bulidSuccess([], '编辑奖品成功');
        }

        return $this->assign(['model' => $model])->fetch();
    }

    public function conf_del()
    {
        if (!$id = $this->post('id', '')) {
            return static::bulidFail('ID非法');
        }

        if (!$model = LotteryAwardModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的奖品');
        }

        if ($model->is_delete == 1) {
            return static::bulidFail('改奖品已删除');
        }

        $model->is_delete = 1;
        if (!$model->save()) {
            return static::bulidFail('删除失败');
        }

        return static::bulidSuccess([], '删除成功');
    }

    public function history()
    {
        if ($this->request->isAjax()) {
            $model = UserLotteryHistoryModel::field('*');

            if (ctype_digit($name = $this->get('name', ''))) {
                $model = $model->where('lottery_award_id', $name);
            }

            if (in_array($award_type = $this->get('award_type'), ['0', '1'])) {
                $model = $model->where('award_type', $award_type);
            }

            return json([
                'count' => $model->count('id'),
                'list' => $model->with([
                    'lottery' => function ($query) {
                        $query->field('id,name');
                    },
                    'lottery_award' => function ($query) {
                        $query->field('id,name,award_pic');
                    },
                    'user_address' => function ($query) {
                        $query->field('id,name,address,mobile');
                    }
                ])
                    ->order('id', 'desc')
                    ->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()
                    ->each(function ($query) {
                        if ($query->draw_time) {
                            $query->draw_time = date('Y-m-d H:i:s', strtotime($query->draw_time));
                        }
                        if ($query->give_time) {
                            $query->give_time = date('Y-m-d H:i:s', strtotime($query->give_time));
                        }
                    })
                    ->toArray(),
                'msg' => '',
                'code' => 0,
            ]);
        }

        return $this->assign(['list' => array_column(LotteryAwardModel::lists(), 'name', 'id')])->fetch();
    }

    public function budan()
    {
        if (!$id = $this->get('id', '')) {
            return static::bulidFail('ID非法');
        }

        if (!$model = UserLotteryHistoryModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的订单记录');
        }

        if ($this->request->isAjax()) {
            if (!ctype_digit($lott_num = $this->post('lott_num', '')) || $lott_num < 1) {
                return static::bulidFail('数量不能小于1');
            }

            $model->express_no = trim($this->post('express_no', ''));
            $model->operator = $this->admin_name;
            $model->lott_num = $lott_num;
            if (!$model->save()) {
                return static::bulidFail('补单失败');
            }

            return static::bulidSuccess([], '补单成功');
        }

        $conf = array_column(LotteryAwardModel::lists(), 'name', 'id');
        $model->name = $conf[$model->lottery_award_id] ?? '';

        return $this->assign(['model' => $model])->fetch();
    }

    public function fahuo()
    {
        if (!$id = $this->get('id', '')) {
            return static::bulidFail('ID非法');
        }

        if (!$model = UserLotteryHistoryModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的订单记录');
        }

        if ($this->request->isAjax()) {
            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('收货人姓名不能为空');
            }

            if (!$mobile = trim($this->post('mobile', ''))) {
                return static::bulidFail('收货人手机不能为空');
            }

            if (!ctype_digit($mobile)) {
                return static::bulidFail('收货人手机错误');
            }

            if (!$address = trim($this->post('address', ''))) {
                return static::bulidFail('收货人地址不能为空');
            }

            if (!$express_no = trim($this->post('express_no', ''))) {
                return static::bulidFail('运单号不能为空');
            }

            if (!ctype_digit($lott_num = $this->post('lott_num', ''))) {
                return static::bulidFail('发货数量错误');
            }

            if (!$userInfo = UserAddressModel::field('id,name,mobile,address')->where('id', $model->user_delivery_id)->where('uid', $model->uid)->find()) {
                $userInfo = new UserAddressModel();
            }

            $userInfo->name = $name;
            $userInfo->mobile = $mobile;
            $userInfo->address = $address;
            $userInfo->uid = $model->uid;
            if (!$userInfo->save()) {
                return static::bulidFail('编辑收货人信息失败');
            }

            $model->user_delivery_id = $userInfo->id;
            $model->operator = $this->admin_name;
            $model->give_status = 1;
            $model->express_no = $express_no;
            $model->lott_num = $lott_num;
            $model->give_time = date('Y-m-d H:i:s');

            if (!$model->save()) {
                return static::bulidFail();
            }

            $this->addAdminLog('为用户:' . $model->uid . ' 进行了发货', $model->uid);

            return static::bulidSuccess();
        }

        $userInfo = new \stdClass();
        $userInfo->name = '';
        $userInfo->mobile = '';
        $userInfo->address = '';

        if ($model->user_delivery_id) {
            if ($userInfoTmp = UserAddressModel::field('name,mobile,address')->where('id', $model->user_delivery_id)->where('uid', $model->uid)->find()) {
                $userInfo = $userInfoTmp;
            }
        }

        $model->user_name = $userInfo->name;
        $model->mobile = $userInfo->mobile;
        $model->address = $userInfo->address;

        $conf = array_column(LotteryAwardModel::lists(), 'name', 'id');
        $model->name = $conf[$model->lottery_award_id] ?? '';
        return $this->assign(['model' => $model])->fetch();
    }
}
